import React from 'react';
import {PageLoading} from '@ant-design/pro-layout';
import {connect, ConnectProps} from 'umi';
import {ConnectState} from '@/models/connect';
import {CurrentUser} from '@/models/user';
import {getToken, setToken, toLogin} from 'chaos-sso-login'
import {get, isEmpty} from "lodash"
interface SecurityLayoutProps extends ConnectProps {
  loading?: boolean;
  currentUser?: CurrentUser;
}
interface SecurityLayoutState {
  isReady: boolean;
}
class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> {
  state: SecurityLayoutState = {
    isReady: false,
  };
  getTokenSuccess = (token: string) => {
    const {dispatch} = this.props;

    if (token) {
      setToken(token);
      if (dispatch) {
        dispatch({
          type: 'user/fetchCurrent',
        }).then((res: any) => {
          let url = new URL(window.location.href)
          let redirectUri = url.searchParams.get("redirect_uri")
          if (redirectUri) {
            window.location.href = redirectUri
          } else {
            window.location.href = "/"
          }
        })
      }
    }
  }
  _getToken() {
    //设置props的token
    if (get(this.props, "user", {}).token == "" && getToken() != "undefined" && getToken() != "") {
      if (this.props.dispatch) {
        this.props.dispatch({
          type: "user/changeToken", payload: getToken()
        })
      }
      return getToken()
    }
    //设置localstorage的token
    else if (get(this.props, "user", {}).token != "" && (getToken() == "undefined" || getToken() == "")) {
      setToken(get(this.props, "user", {}).token)
      return get(this.props, "user", {}).token
    }
    //都有就随便取了
    else if (get(this.props, "user", {}).token != "" || (getToken() != "undefined" && getToken() != "")) {
      return get(this.props, "user", {}).token || getToken()
    }
    return false
  }
  componentDidMount() {

    const {dispatch, user} = this.props;
    let userInit = isEmpty(get(user, "currentUser", {})) ? false : true
    if (dispatch) {

      //先从props取token，没有再到localstorage里面取
      let token = this._getToken()
      if (token) {
        if (userInit) {
          this.setState({
            isReady: true,
          });
        } else {
          dispatch({
            type: 'user/fetchCurrent',
          }).then((res: any) => {

            this.setState({
              isReady: true,
            });
          })
        }
      }
      //取code换token
      else {

        let url = new URL(window.location.href)
        let code = url.searchParams.get("code")
        let redirectUri = url.searchParams.get("redirect_uri")
        if (code && redirectUri) {
          dispatch({
            type: "user/fetchToken",
            payload: {
              code, redirectUri
            }
          }).then((res: any) => {
            this.getTokenSuccess(get(this.props, "user", {}).token)
          }).catch((error: any) => {
          })
        } else {

          toLogin()
        }
      }
    }
  }
  render() {
    const {isReady} = this.state;
    const {children} = this.props;
    if (!isReady) {
      return <PageLoading/>;
    }
    return children;
  }
}
export default connect(({user, loading}: ConnectState) => ({
  user: user,
  loading: loading.models.user,
}))(SecurityLayout);
